package cn.jiguang.hxhg.utils;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;

import javax.crypto.Cipher;

import cn.jiguang.verifysdk.api.VerifyListener;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import okhttp3.Response;

public class PhoneUtils {
    private static final Base64.Decoder decoder = Base64.getDecoder();
    private static final Base64.Encoder encoder = Base64.getEncoder();
    private static final String TAG = "PhoneUtils";
    /**
     * 极光后台应用设置里面的appkey
     */
    private static String appKey = "1305669773ce0203d6a5a15f";

    /**
     * 极光后台应用设置里面的masterSecret
     */
    private static String masterSecret = "45ceba5f0723e48900cc9ceb";

    /**
     * RSA私钥 http://web.chacuo.net/netrsakeypair 不需要证书密码
     */
    private static String priKey = "MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBAMyB4wQd/2sYsXojVxqarta1PBLudiVcqse+V4C8R+V9AWI9ap66uqPXXwPXNWY1YpL6nMknq10sumYkG+wVPUh6PDTQ5uRTEtz0kND+oua7DGWKuNdZFgfawy8JRCZfH7arX7Dsv+5u4cDvF471yHHHUk2TxceKyIyQxGyWBvyhAgMBAAECgYEAqL5Tz0XhR0Es0Bbw/Ga99TO9yfExU0rPL9mC4hp5SIaI6cK7gxWYgzBmmgitaxSJrbVUQTaWU19gvn70+yvbT8TA+enxtAN06pB0bXgZhe97fvNnReS5BUROR4lsjyex2HzqSlP6XWsQjme/KL8vWvs+UcLq8SvvnojizgyGarECQQDpVtALzqI3ry2zYmVV+1v3b63TSyGYIPpw73KhNWuabEakm2i1pW35Jb7oa5MbLepEmshg0BB72xSGFQJ5+WITAkEA4F5FOiRUkHy1dZBedSvg2ATMjTpZOx7atvAachMLV1bIB4LSpdvVvgYeIEkFMoZB2b30MqdMpDyXkXyJpEdc+wJBALBsGesDdbUidyxNNg83eIZx4vyBrsnGDXT8JjBrIotkWFk2w4mrpaWd+2ThiR0gryLl4KEKT5xFvZPPKMsuWg8CQQC3nw8i1UbL9PQA4gUb+awKvmq1jjImu0qd+wR5pXJbqS8NTpicmrxjxtfy7i+tuMi9rcLjjZ2gr+IPdA+lfa3vAkB3uU9CtFxwTe3Kv1CRlSkGnnnoFd+Mw4GwH5U3h0NlbhLnqFVM8RMVVsvvWWXKtqC0iAGGGlWaa7BpLh7LX6f5";

    public interface GetPhoneListener {
        void onSuccess(String phone);
    }

    /**
     * 获取手机号码
     */
    public static void sendLoginTokenVerify(final Context context, String loginToken, final GetPhoneListener getPhoneListener) {
        String url = "https://api.verification.jpush.cn/v1/web/loginTokenVerify";
        MediaType JSON = MediaType.parse("application/json;charset=utf-8");
        String authorization = "Basic " + encode(appKey + ":" + masterSecret);
        JSONObject json = new JSONObject();
        try {
            json.put("loginToken", loginToken);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        OkHttpClient okHttpClient = new OkHttpClient();
        RequestBody requestBody = RequestBody.create(JSON, String.valueOf(json));

        final okhttp3.Request request = new okhttp3.Request.Builder()
                .url(url)
                .post(requestBody)
                .addHeader("Authorization", authorization)
                .build();

        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(context, e.getMessage(), Toast.LENGTH_LONG).show();
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String phoneRsp = response.body().string();

                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
                        String encodePhone = "";
                        try {
                            JSONObject jsonObject = new JSONObject(phoneRsp);
                            int code = jsonObject.getInt("code");
                            if (code == 8000)
                                encodePhone = jsonObject.getString("phone");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        if (!TextUtils.isEmpty(encodePhone)) {
                            Toast.makeText(context, "获取手机号成功", Toast.LENGTH_SHORT).show();

                            try {
                                String phone = decrypt(encodePhone);
                                if (!TextUtils.isEmpty(encodePhone)) {
                                    Toast.makeText(context, "解密手机号成功：" + phone, Toast.LENGTH_LONG).show();
                                    getPhoneListener.onSuccess(phone);
                                } else {
                                    Toast.makeText(context, "解密手机号失败：" + phone, Toast.LENGTH_LONG).show();
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                                Toast.makeText(context, "解密手机号失败：" + e.getMessage(), Toast.LENGTH_LONG).show();
                            }
                        } else {
                            Toast.makeText(context, "获取手机号失败", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }
        });
    }

    /**
     * 验证手机号码
     */
    public static void sendVerify(final Context context, String phone, String token, String operator, VerifyListener listener) {
        String url = "https://api.verification.jpush.cn/v1/web/verify";
        MediaType JSON = MediaType.parse("application/json;charset=utf-8");
        String authorization = "Basic " + encode(appKey + ":" + masterSecret);
        JSONObject json = new JSONObject();
        try {
            json.put("phone", phone);
            json.put("token", token);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        OkHttpClient okHttpClient = new OkHttpClient();
        RequestBody requestBody = RequestBody.create(JSON, String.valueOf(json));

        final okhttp3.Request request = new okhttp3.Request.Builder()
                .url(url)
                .post(requestBody)
                .addHeader("Authorization", authorization)
                .build();

        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(context, e.getMessage(), Toast.LENGTH_LONG).show();
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                int code;
                String responseData;
                String content = null;
                try {
                    responseData = response.body().string();
                    code = response.code();

                    Log.d(TAG, "response code = " + code + " ，msg = " + responseData);
                    if (code != 200) {
                        code = -1;
                        content = "net error";
                    } else {
                        Log.d(TAG, "verify number, code=" + code + " content=" + responseData);
                        JSONObject resultJson = new JSONObject(responseData);
                        code = resultJson.optInt("code");
                        if (code == 9000) {
                            content = "verify consistent";
                        } else if (code == 9001) {
                            content = "verify not consistent";
                        } else if (code == 9002) {
                            content = "unknown result";
                        } else if (code == 9003) {
                            content = "token expired or not exist";
                        } else if (code == 9004) {
                            content = "config not found";
                        } else if (code == 9005) {
                            content = "verify interval is less than the minimum limit";
                        } else if (code == 9006) {
                            content = "frequency of verifying single number is beyond the maximum limit";
                        } else if (code == 9007) {
                            content = "beyond daily frequency limit";
                        } else if (code == 9010) {
                            content = "miss auth";
                        } else if (code == 9011) {
                            content = "auth failed";
                        } else if (code == 9012) {
                            content = "parameter invalid";
                        } else if (code == 9013) {
                            content = "request method not supported";
                        } else if (code == 9015) {
                            content = "http media type not supported";
                        } else if (code == 9018) {
                            content = "appKey no money";
                        } else if (code == 9031) {
                            content = "not validate user";
                        } else if (code == 9099) {
                            content = "bad server";
                        }
                    }

                } catch (Throwable e) {
                    Log.w(TAG, "phone validate e:" + e);
                    code = -1;
                    content = e.toString();
                }

                listener.onResult(code, content, operator);
            }
        });
    }

    /**
     * 请求头加密
     */
    public static String encode(String text) {
        byte[] textByte = new byte[0];
        try {
            textByte = text.getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return encoder.encodeToString(textByte);
    }

    /**
     * 解密加密手机号
     */
    public static String decrypt(String encodePhone) throws Exception {
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(priKey));
        PrivateKey privateKey = KeyFactory.getInstance("RSA").generatePrivate(keySpec);

        // 服务端解密需要修改Cipher.getInstance("RSA")
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] b = decoder.decode(encodePhone.getBytes("UTF-8"));
        return new String(cipher.doFinal(b));
    }
}
